<?php


namespace App\Http\service;


use App\Engine\TokenService;
use App\Jobs\UserLoginJob;
use App\Models\Image;
use App\Models\Sys;
use EasyWeChat\Factory;
use App\Exceptions\ApiException;
use App\Models\User as UserModel;
use Illuminate\Support\Facades\Log;

class XcxService
{
    private $config;
    private $sysModel;
    private $userModel;
    private $app;

    public function __construct()
    {
        $this->sysModel=new Sys();
        $this->userModel=new UserModel();
        $this->config=[
            'app_id'=>$this->sysModel->get_Value("wx_appid"),
            'secret'=>$this->sysModel->get_Value("wx_secret"),
            'response_type'=>'array',
            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/wechat.log',
            ],
        ];
        $this->app=Factory::miniProgram($this->config);
    }



    public function create_xcx_code($scene)
    {
        $response =$this->app->app_code->getUnlimit($scene);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse){
            $name=md5($scene).".jpg";
            $filename = $response->saveAs(public_path()."/uploads/code/",$name);
            $url="uploads/code/".$name;
            $image=[
                "url"=>$url
            ];
            Image::create($image);
            return $url;
        }else{
            throw new ApiException("小程序生成失败");
        }
    }

    public function send_temp()
    {
        $res=$this->app->subscribe_message->send([
            'touser' => "oDKch5PgPBZkf-hamipv47r0Ce4k",
            'template_id' => 'Yx37_YLd-8fB1ha8IBvQtA4f0G4eGSfgPJFmiHleG8I',
            'page' => 'pages/chat/chat',
            'data'=>[
                'thing2'=>[
                    'value'=>'您好'
                ],
                'time3'=>[
                    'value'=>date("Y-m-d H:i:S")
                ]
            ]
        ]);
        return $res;
    }

    public function get_session($code)
    {
        $wxResult=$this->app->auth->session($code);
        if(empty($wxResult)) {
            throw new ApiException('获取session_key及openID时异常，微信内部错误');
        }
        $loginFail = array_key_exists('errcode', $wxResult);
        if ($loginFail){
            throw new ApiException($loginFail['errmsg']);
        }
        return $wxResult["session_key"];
    }

    /**小程序登录
     * @param $code
     * @param string $invite_uid
     * @return array
     * @throws ApiException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function xcx_login($code,$invite_uid="")
    {
        $userModel=new UserModel();
        $wxResult=$this->app->auth->session($code);
        $is_newUser=false;

        if(empty($wxResult)) {
            throw new ApiException('获取session_key及openID时异常，微信内部错误');
        }
        $loginFail = array_key_exists('errcode', $wxResult);
        if ($loginFail){
            throw new ApiException($loginFail['errmsg']);
        }


        $user=$this->userModel->where("openid",$wxResult["openid"])->first();
        if(!$user){
            $create=[
                "openid"=>$wxResult["openid"],
                "session_key"=>$wxResult["session_key"],
                "login_time"=>time(),
                "points"=>0,
                "egg"=>0,
                "invite_uid"=>$invite_uid,
                "draw_times"=>0,
                'food'=>0,
                'balance'=>0,
                'tree'=>0,
                "platform"=>"xcx",
                "coupon"=>0
            ];
            if (isset($wxResult["unionid"])){
                $create["unionid"]=$wxResult["unionid"];
            }
            $userModel->create($create);
            $user=$this->userModel->where("openid",$wxResult["openid"])->first();
            $is_newUser=true;
        }else{
            if (isset($wxResult["unionid"])){
               $this->userModel->where("id",$user["id"])->update(["unionid"=>$wxResult["unionid"]]);
            }
        }
        $cache=[
            "uid"=>$user["id"]
        ];
        UserLoginJob::dispatch($user);
        $token=(new TokenService())->saveCache($cache);
        return ["token"=>$token,'is_newUser'=>$is_newUser];
    }


    /**创建直播间
     * @param $data
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function create_live_room($data)
    {
        $url="wxaapi/broadcast/room/create";
        $res=$this->app->auth->httpPost($url,$data);
        return $res;
    }

    public function get_live($start=0)
    {
        $res=$this->app->live->getRooms($start);
        return $res;
    }

    public function getPlaybacks($id)
    {
        $res=$this->app->live->getPlaybacks($id);
        return $res;
    }
}
